import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', {
  state: () => ({
    user: null,
    events: [],
    venues: [],
    orders: [],
    cart: JSON.parse(localStorage.getItem('cart')) || []
  }),
  actions: {
    setUser(user) {
      this.user = user
    },
    addEvent(event) {
      this.events.push(event)
    },
    updateEvent(updatedEvent) {
      const index = this.events.findIndex(e => e.id === updatedEvent.id)
      if (index !== -1) {
        this.events[index] = updatedEvent
      }
    },
    deleteEvent(eventId) {
      this.events = this.events.filter(e => e.id !== eventId)
    },
    addToCart(event) {
      this.cart.push(event)
      // 持久化到localStorage
      localStorage.setItem('cart', JSON.stringify(this.cart))
    },
    removeFromCart(eventId) {
      this.cart = this.cart.filter(item => item.id !== eventId)
      // 持久化到localStorage
      localStorage.setItem('cart', JSON.stringify(this.cart))
    },
    clearCart() {
      this.cart = []
      // 持久化到localStorage
      localStorage.setItem('cart', JSON.stringify(this.cart))
    }
  },
  getters: {
    cartCount: (state) => state.cart.length,
    isLoggedIn: (state) => !!state.user
  }
})